package com.whty.cms.filewps.common.interceptor;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.whty.cms.filewps.common.message.ResponseMessage;
import com.whty.cms.filewps.config.dto.ApplyInfo;
import com.whty.cms.filewps.config.service.IApplyInfoService;
import com.whty.cms.filewps.util.CryptoClient;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 
 * @author sz
 *
 */

public class AuthorizationInterceptor extends HandlerInterceptorAdapter {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(AuthorizationInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object obj) throws Exception {
		
		// 无需认证
		if (!needAuth(request)) {
			return true;
		}
		
		// 强制需要认证或者三方应用外网调用需要认证
		String appId = request.getHeader("appId");
		String timestamp = request.getHeader("Timestamp");
		String signature = request.getHeader("Signature");
		LOGGER.info("AppId={}, Timestamp={}, Signature={}", appId, timestamp, signature);
		if (StringUtils.isBlank(appId) || StringUtils.isBlank(timestamp) || StringUtils.isBlank(signature)) {
			ResponseMessage responseMessage = ResponseMessage.getFailedResponse();
			responseMessage.setCode("100201");
			responseMessage.setMsg("认证失败[AppId,Timestamp,signature不能为空]");
			responseToJson(response, responseMessage);
			return false;
		}
		
		BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
		IApplyInfoService applyInfoService = (IApplyInfoService) factory.getBean("applyInfoService");
		if (applyInfoService == null) {
			ResponseMessage responseMessage = ResponseMessage.getFailedResponse();
			responseMessage.setCode("200202");
			responseMessage.setMsg("认证失败[服务器内部错误]");
			responseToJson(response, responseMessage);
			return false;
		}
		ApplyInfo app = applyInfoService.selectByPrimaryKey(appId);
		if (app == null) {
			ResponseMessage responseMessage = ResponseMessage.getFailedResponse();
			responseMessage.setCode("100202");
			responseMessage.setMsg("认证失败[无效应用AppId=" + appId + "]");
			responseToJson(response, responseMessage);
			return false;
		}
		
		request.setAttribute("appName", app.getAppName());
		request.setAttribute("app", app);
		try {
			Long.valueOf(timestamp);
		} catch(Exception ex) {
			ResponseMessage responseMessage = ResponseMessage.getFailedResponse();
			responseMessage.setCode("100203");
			responseMessage.setMsg("认证失败[时间戳异常Timestamp=" + timestamp + "]");
			responseToJson(response, responseMessage);
			return false;
		}
		
		if (!verifyTimestamp(Long.valueOf(timestamp))) {
			ResponseMessage responseMessage = ResponseMessage.getFailedResponse();
			responseMessage.setCode("100204");
			responseMessage.setMsg("认证失败[请求过期]");
			responseToJson(response, responseMessage);
			return false;
		}
		
		String httpMethod = request.getMethod();
	    String uri = request.getRequestURI();
	    String contextPath = request.getContextPath();
	    if (StringUtils.length(contextPath) > 0) {
	        uri = StringUtils.substring(uri, contextPath.length());
	    }
		String authorization = appId + "&" + httpMethod + "&" + uri + "&" + timestamp;
		String publicKey = String.valueOf(app.getPublicKey());
		
		CryptoClient client = CryptoClient.getInstance(publicKey);
		if (!client.verify(authorization, signature)) {
			ResponseMessage responseMessage = ResponseMessage.getFailedResponse();
			responseMessage.setCode("100205");
			responseMessage.setMsg("认证失败[签名错误]");
			responseToJson(response, responseMessage);
			return false;
		}

		return true;
	}
	
	private boolean verifyTimestamp(Long timestamp) {
		Calendar verify = Calendar.getInstance();
		verify.setTimeInMillis(timestamp);
		
		java.util.Date now = new java.util.Date();
		Calendar more = Calendar.getInstance();
		more.setTime(now);
		more.add(Calendar.MINUTE, 5);
		
		Calendar less = Calendar.getInstance();
		less.setTime(now);
		less.add(Calendar.MINUTE, -5);
		
		return verify.after(less) && verify.before(more);
	}
	
	private boolean needAuth(HttpServletRequest request) {
		String ip = request.getServerName();
		LOGGER.info("serverName=>{}", ip);
		String reg = "(10|172|192)\\.([0-9][0-9]{0,2}|[2][0-5]{0,2}|[3-9][0-9]{0,1})\\.([0-9][0-9]{0,2}|[2][0-5]{0,2}|[3-9][0-9]{0,1})\\.([0-9][0-9]{0,2}|[2][0-5]{0,2}|[3-9][0-9]{0,1})";// 正则表达式=。																																							// =、懒得做文字处理了、
		Pattern p = Pattern.compile(reg);
		Matcher matcher = p.matcher(ip);
		return !matcher.find();
	}
	
	private void responseToJson(HttpServletResponse response, Object obj) {
        response.setContentType("application/json;charset=UTF-8");
        BufferedOutputStream out = null;
        ByteArrayInputStream in = null;
        String result;
        if (obj instanceof String) {
            result = obj.toString();
        } else {
            result = JSON.toJSONString(obj, SerializerFeature.WriteDateUseDateFormat);
        }
        try {
            out = new BufferedOutputStream(response.getOutputStream());
            in = new ByteArrayInputStream(result.getBytes("UTF-8"));
            byte[] buff = new byte[1024 * 512];
            int len;
            while ((len = in.read(buff)) > 0) {
                out.write(buff, 0, len);
            }
            out.flush();
        } catch(IOException ex) {
            LOGGER.error(ex.getMessage(), ex);
        } finally {
            try {
                if (out != null) out.close();
                if (in != null) in.close();
            } catch(IOException ex) {
                LOGGER.error(ex.getMessage(), ex);
            }
        }
    }

}
